package com.liyuhan.shopping.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.liyuhan.shopping.dto.DataRequest;
import com.liyuhan.shopping.dto.DataResponse;
import com.liyuhan.shopping.entity.User;
import com.liyuhan.shopping.mapper.UserMapper;
import com.liyuhan.shopping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    // 定义返回数据结构
    private Map<String, String> map = new HashMap<>();

    // 注入
    @Autowired
    private UserMapper userMapper;

    public DataResponse login(JSONObject request){
        // 解析用户提交的表单数据
        String username = request.get("username").toString();
        String password = request.get("password").toString();
        // 查找符合条件的用户
        User user = userMapper.selectByUsername(username);
        // 对信息进行校验
        if(user == null){
            // 没有该用户名
            map.put("message", "用户名未注册！");
            return new DataResponse("0", map);
        }else{
            // 密码输入错误
            if(!user.getPassword().equals(password)){
                map.put("message", "密码错误！");
                return new DataResponse("0", map);
            }
        }
        // 登录成功
        return new DataResponse("200", map);
    }

    public DataResponse register(JSONObject request){
        // 获取参数
        String username = request.get("username").toString();
        String password = request.get("password").toString();

        // 注册逻辑
        User user = userMapper.selectByUsername(username);
        if(user != null){
            // 用户名已存在
            map.put("message", "用户名已存在！");
            return new DataResponse("0", map);
        }else{
            // 完成注册
            userMapper.insert(new User(username, password));
        }

        // 返回响应
        return new DataResponse("200", map);
    }
}
